/*
Designer   : Renyangang

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package device

import (
	"context"
	"encoding/binary"
	"fpga-vboard/logger"
	"fpga-vboard/pins"
)

func init() {
	config := &FlashConfig{
		DeviceInfo: DeviceInfo{
			Id:         FLASH_DEFAULT,
			Type:       FLASH,
			Name:       "Flash",
			IsOptional: true,
			Enable:     false,
			InputPins:  pins.NewPinDefs([]string{"default_flash_addr", "default_flash_read_en", "default_flash_write_en", "default_flash_byte_size", "default_flash_wdata"}, []uint{32, 1, 1, 3, 8}, pins.PinDirectionInput),
			OutputPins: pins.NewPinDefs([]string{"default_flash_data", "default_flash_ready"}, []uint{8, 1}, pins.PinDirectionOutput),
		},
		Size:     256,
		FilePath: "",
	}
	RegisterDev(config)
}

type Flash struct {
	*DeviceBase
	store *Storage
}

func NewFlash(config *FlashConfig) *Flash {
	var flash *Flash
	var err error
	if config.FilePath == "" {
		flash = innertCreate(NewStorage(config.Size))
	} else {
		flash, err = CreateWithFile(config.FilePath)
		if err != nil {
			logger.FatalEvent("Failed to create flash storage, %v", err)
			return nil
		}
	}
	flash.DeviceBase = &DeviceBase{
		Config: config,
	}
	return flash
}

func CreateWithFile(path string) (*Flash, error) {
	store, err := CreateStorageWithFile(path)
	if err != nil {
		return nil, err
	}
	return innertCreate(store), nil
}

func innertCreate(store *Storage) *Flash {
	return &Flash{
		store: store,
	}
}

func (f *Flash) Read(addr []byte) byte {
	return f.store.Read(binary.LittleEndian.Uint32(addr))
}

func (f *Flash) Run(ctx context.Context) {
	if f.GetPinBool("default_flash_read_en") {
		f.SetPinByte("default_flash_data", f.Read(f.GetPinBytes("default_flash_addr")))
		f.SetPinBool("default_flash_ready", true)
	} else {
		f.SetPinBool("default_flash_ready", false)
	}
}
